class Complex {
private double real;
private double imag;
// 构造函数
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
// 获取实部
public double getReal() {
return real;
}
// 获取虚部
public double getImag() {
return imag;
}
// 加法
public Complex add(Complex other) {
double newReal = this.real + other.real;
double newImag = this.imag + other.imag;
return new Complex(newReal, newImag);
}
// 减法
public Complex subtract(Complex other) {
double newReal = this.real - other.real;
double newImag = this.imag - other.imag;
return new Complex(newReal, newImag);
}
// 乘法
public Complex multiply(Complex other) {
double newReal = this.real * other.real - this.imag * other.imag;
double newImag = this.real * other.imag + this.imag * other.real;
return new Complex(newReal, newImag);
}
// 除法
public Complex divide(Complex other) {
double denominator = other.real * other.real + other.imag * other.imag;
double newReal = (this.real * other.real + this.imag * other.imag) / denominator;
double newImag = (this.imag * other.real - this.real * other.imag) / denominator;
return new Complex(newReal, newImag);
}
@Override
public String toString() {
if (imag == 0) {
return String.valueOf(real);
} else if (real == 0) {
return imag + "i";
} else if (imag < 0) {
return real + " - " + (-imag) + "i";
} else {
return real + " + " + imag + "i";
}
}
}
class Main {
public static void main(String[] args) {
Complex c1 = new Complex(1, 2);
Complex c2 = new Complex(3, 4);
System.out.println("加法: " + c1.add(c2));
System.out.println("减法: " + c1.subtract(c2));
System.out.println("乘法: " + c1.multiply(c2));
System.out.println("除法: " + c1.divide(c2));
}
}